<template>
    <div class="wrap normal">
        <!-- 搜索条件 -->
        <div class="wrap-form" id="wrap-form">
            <el-row>
                <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                    <div class="left-panel">
                        <el-button type="primary" icon="el-icon-plus" v-hasPerm="'system:departManage:add'" @click="pageOperate('add')">添加</el-button>
                        <el-button icon="el-icon-refresh" @click="pageOperate('refresh')">刷新</el-button>
                    </div>
                </el-col>
            </el-row>
        </div>
        <!-- table数据 -->
        <div class="wrap-table">
            <el-table :data="tableData" border :max-height="tableMaxHeight" v-loading="tableLoading" :header-cell-style="{ background: '#F5F6FA' }" style="width: 100%" row-key="id" default-expand-all :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" @sort-change="tableSortChange">
                <el-table-column type="index" label="序号" width="60" align="center"> </el-table-column>
                <el-table-column prop="name" label="部门名称" min-width="200"></el-table-column>
                <el-table-column prop="status" label="状态" min-width="100">
                    <template slot-scope="scope">
                        <el-tag :type="$options.filters.filterStatusClass(scope.row.status)">{{ scope.row.status | filterStatus }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="sort" label="排序" min-width="80" sortable="custom"> </el-table-column>
                <el-table-column label="操作" width="120" fixed="right">
                    <template slot-scope="scope">
                        <el-button type="text" v-hasPerm="'system:departManage:add'" @click="pageOperate('add', scope.row)">添加</el-button>
                        <el-button type="text" v-hasPerm="'system:departManage:edit'" @click="pageOperate('edit', scope.row)">修改</el-button>
                        <el-button type="text" v-hasPerm="'system:departManage:delete'" @click="pageOperate('deleteOne', scope.row)" :disabled="scope.row.parentId === '0'">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- dialog -->
        <el-dialog v-if="operateDialog" :title="operateTitle" :visible.sync="operateDialog" @close="closeOperateDialog" :width="`${operateWidth}px`" :close-on-press-escape="false" :close-on-click-modal="false">
            <el-form ref="operateForm" :model="operateForm" :rules="operateRules" label-width="100px">
                <el-form-item label="上级部门" prop="parentName" v-if="operateForm.parentId !== '0' && deptOptions.length > 0">
                    <el-select class="tree-select" ref="treeSelect" v-model="operateForm.parentName" placeholder="请选择上级部门" :popper-append-to-body="false" style="width: 100%">
                        <el-option :value="operateForm.parentId" style="height: 100%">
                            <el-tree :data="deptOptions" :props="defaultProps" default-expand-all :expand-on-click-node="false" node-key="id" @node-click="handleNodeClick">
                                <span class="custom-tree-node" :class="data.id === operateForm.parentId ? 'checked' : ''" slot-scope="{ node, data }">{{ node.label }}</span>
                            </el-tree>
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="部门名称" prop="name">
                    <el-input v-model="operateForm.name" clearable placeholder="请输入部门名称" />
                </el-form-item>
                <el-form-item label="显示排序" prop="sort">
                    <el-input-number v-model="operateForm.sort" size="small" :min="0" />
                </el-form-item>
                <el-form-item label="部门状态" prop="status">
                    <el-radio-group v-model="operateForm.status">
                        <el-radio v-for="(item, index) in statusOptions" :label="item.value" :key="index">{{ item.label }}</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="closeOperateDialog">取 消</el-button>
                <el-button type="primary" :loading="operateLoading" @click="operateSubmit">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { treeToArray } from '@/utils/index'
import tableHeight from '@/mixins/tableHeight'
import { statusOptions } from '@/filters/options'
import { getDepartList, deleteDepart, addOrUpdateDepart } from '@/api/system'
export default {
    name: 'DeparManage',
    mixins: [tableHeight],
    data() {
        return {
            form: {
                fieldSort: '',
                orderSort: ''
            },
            tableData: [],
            tableLoading: false,
            // 类型
            operateType: '',
            // 标题
            operateTitle: '',
            // 弹框
            operateDialog: false,
            // 宽度
            operateWidth: 550,
            // loading
            operateLoading: false,
            // 操作form
            operateForm: {
                id: '',
                parentName: '',
                parentId: '',
                name: '',
                sort: 1,
                status: 1
            },
            // 校验规则
            operateRules: {
                parentName: [
                    { required: true, message: '请选择上级部门', trigger: ['blur', 'change'] }
                ],
                name: [
                    { required: true, message: '请输入部门名称', trigger: ['blur'] }
                ],
                sort: [
                    { required: true, message: '请输入排序', trigger: ['blur', 'change'] }
                ],
                status: [
                    { required: true, message: '请选择部门状态', trigger: ['blur', 'change'] }
                ]
            },
            // 部门树
            deptOptions: [],
            // 部门选型属性配置
            defaultProps: {
                label: 'name',
                children: "children"
            },
            // 状态选项
            statusOptions
        }
    },
    methods: {
        // 排序
        tableSortChange(data) {
            this.form.fieldSort = data.prop
            this.form.orderSort = data.order
            this.getTableData()
        },
        // 数据
        getTableData() {
            this.tableLoading = true
            getDepartList({}).then(res => {
                this.tableLoading = false
                this.tableData = res.data
                this.deptOptions = res.data
            }).catch(error => {
                this.tableLoading = false
            })
        },
        // 操作
        pageOperate(type, row) {
            this.operateType = type
            switch (type) {
                case 'search':
                    this.getTableData()
                    break;
                case 'refresh':
                    Object.assign(this.$data, this.$options.data())
                    this.getTableData()
                    break;
                case 'add':
                    this.operateDialog = true
                    this.operateTitle = '添加部门'
                    if (row) {
                        this.operateForm.parentName = row.name
                        this.operateForm.parentId = row.id
                    }
                    break;
                case 'edit':
                    this.operateDialog = true
                    this.operateTitle = '修改部门信息'
                    for (let key in this.operateForm) {
                        if (key === 'parentName' && row.parentId !== '0') {
                            let deptList = treeToArray(this.deptOptions)
                            let parentName = deptList.filter(item => item.id === row.parentId)[0].name
                            this.operateForm[key] = parentName
                        } else {
                            this.operateForm[key] = row[key]
                        }
                    }
                    break;
                case 'deleteOne':
                    this.$confirm('确认删除该部门?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        deleteDepart({ id: row.id }).then(res => {
                            this.getTableData()
                            this.$message_tip(`删除成功`, 'success')
                        }).catch(error => { })
                    }).catch(() => { });
                    break;
                default:
                    break;
            }
        },
        // 选择部门
        handleNodeClick(data) {
            this.operateForm.parentName = data.name;
            this.operateForm.parentId = data.id
            this.$refs.treeSelect.blur()
        },
        // 关闭操作按钮
        closeOperateDialog() {
            this.operateLoading = false
            this.operateDialog = false
            this.operateTitle = ''
            this.operateType = ''
            this.operateForm = this.$options.data().operateForm
        },
        // 提交
        operateSubmit() {
            this.$refs.operateForm.validate(valid => {
                if (valid) {
                    let formData = JSON.parse(JSON.stringify(this.operateForm))
                    delete formData.parentName
                    formData.parentId = formData.parentId ? formData.parentId : '0'
                    if (formData.parentId === formData.id) return this.$message_tip('请选择正确的上级部门', 'error')
                    if (this.operateType === 'add' || this.operateType === 'edit') {
                        this.operateLoading = true
                        addOrUpdateDepart(formData).then(res => {
                            this.getTableData()
                            this.$message_tip(`${this.operateTitle}成功`, 'success')
                            this.closeOperateDialog()
                        }).catch(error => {
                            this.operateLoading = false
                        })
                    }
                }
            })
        }
    },
    mounted() {
        this.getTableData()
    }
}
</script>

<style lang="scss" scoped>
.el-dialog__body {
    .el-form {
        .el-select-dropdown {
            .el-select-dropdown__item {
                padding: 0 0;
            }
            .el-select-dropdown__item.selected {
                color: inherit;
                font-weight: normal;
            }
        }
    }
}

::v-deep {
    .el-tree {
        .el-tree-node {
            .el-tree-node__content {
                .el-tree-node__expand-icon {
                    margin-left: 8px;
                }
                .custom-tree-node.checked {
                    color: #409eff;
                }
            }
        }
    }
}
</style>